212E - IT Restaurants - CodeForces Solution


dfs and similar dp trees *1500

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
using namespace std;
#define pb emplace_back
#define endl "\n"

const int N=5e3+100;
bitset<5005> ans;
int sz[N],head[N],ver[2*N],Next[2*N];
int tot,n;

void add(int x,int y)
{
	ver[++tot]=y; Next[tot]=head[x]; head[x]=tot;
	ver[++tot]=x; Next[tot]=head[y]; head[y]=tot;
}

void dfs(int x,int fa)
{
	sz[x]=1;
	int sums=0;
	bitset<5005> dp;
	dp[0]=1;
	for(int i=head[x];i;i=Next[i]){
		int y=ver[i];
		if(y==fa) continue;
		dfs(y,x);
		sums+=sz[y];
		for(int j=n;j>=sz[y];j--){
			if(dp[j-sz[y]]) dp[j]=1;
		}
	}
	if(sums==0) return;
	int now=n-1-sums;
	for(int j=n;j>=now;j--){
		if(dp[j-now]) dp[j]=1;
	}
	ans|=dp;
	sz[x]+=sums;
}

void solve()
{
	cin>>n;
	for(int i=1;i<=n-1;i++){
		int u,v;
		cin>>u>>v;
		add(u,v);
	}
	dfs(1,0);
	int tot=0;
	for(int i=1;i<n-1;i++) if(ans[i]) tot++;
	cout<<tot<<endl;
	for(int i=1;i<n-1;i++){
		if(ans[i]) cout<<i<<" "<<(n-1-i)<<endl;
	}
}

signed main()
{
	ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
	int t;
	// cin>>t;
	t=1;
	while(t--){
		solve();
	}
	return 0;
}
 	 	  	 	 		 		 	 	  			 			 	


Comments

Submit
0 Comments
More Questions

1302. Deepest Leaves Sum
1209. Remove All Adjacent Duplicates in String II
994. Rotting Oranges
983. Minimum Cost For Tickets
973. K Closest Points to Origin
969. Pancake Sorting
967. Numbers With Same Consecutive Differences
957. Prison Cells After N Days
946. Validate Stack Sequences
921. Minimum Add to Make Parentheses Valid
881. Boats to Save People
497. Random Point in Non-overlapping Rectangles
528. Random Pick with Weight
470. Implement Rand10() Using Rand7()
866. Prime Palindrome
1516A - Tit for Tat
622. Design Circular Queue
814. Binary Tree Pruning
791. Custom Sort String
787. Cheapest Flights Within K Stops
779. K-th Symbol in Grammar
701. Insert into a Binary Search Tree
429. N-ary Tree Level Order Traversal
739. Daily Temperatures
647. Palindromic Substrings
583. Delete Operation for Two Strings
518. Coin Change 2
516. Longest Palindromic Subsequence
468. Validate IP Address
450. Delete Node in a BST